(function() {
    var feedback = {
        msgcontent: document.getElementById('msgcontent'),
        msgtype: document.getElementById('msgtype'),
        videoContainer: document.getElementById('video-container'),
        sendMsgBtn: document.getElementById('sendMsgBtn'),
        //privatea:document.getElementById('privatea'),
        sendtype: document.getElementById('sendtype'),
        msgvideo: document.getElementById('msgvideo')
    };
    var url = Apiurl+'index/noticeadd';
    var size = null;
    feedback.files = [];
    feedback.uploader = null;
    feedback.deviceInfo = null;
    mui.plusReady(function() {
        //设备信息，无需修改
        feedback.deviceInfo = {
            appid: plus.runtime.appid,
            imei: plus.device.imei, //设备标识
            video: feedback.files, //图片文件
            p: mui.os.android ? 'a' : 'i', //平台类型，i表示iOS平台，a表示Android平台。
            md: plus.device.model, //设备型号
            app_version: plus.runtime.version,
            plus_version: plus.runtime.innerVersion, //基座版本号
            os: mui.os.version,
            net: '' + plus.networkinfo.getCurrentType()
        }
    });
    /**
     *提交成功之后，恢复表单项 
     */
    feedback.clearForm = function() {
        feedback.msgcontent.value = '';
        feedback.msgtype.value = '';
        feedback.sendtype.value = '';
        feedback.videoContainer.innerHTML = '';
        feedback.newPlaceholder();
        feedback.files = null;
        size = 0;
    };
    feedback.addFile = function(path) {
        feedback.files.push({
            name: "video",
            path: path,
            id: "video"
        });
    };
    /**
     * 初始化图片域占位
     */
    feedback.newPlaceholder = function() {
        var placeholder = document.createElement('div');
        placeholder.setAttribute('class', 'image-item space');
        //加号和框
        var up = document.createElement("div");
        up.setAttribute('class', 'image-up');
        up.setAttribute('id', 'image-up');
        var fileInput = document.createElement('div');
        fileInput.setAttribute('class', 'file');
        fileInput.setAttribute('id', 'msgvideo');
        up.addEventListener('tap', function(event) {
            // var btnArray = [{
            //     title: "录像"
            // }, {
            //     title: "从相册选取"
            // }];

            // plus.nativeUI.actionSheet({
            //     title: "选择类型",
            //     cancel: "取消",
            //     buttons: btnArray
            // }, function(actionindex) {
            //     var actionindex = actionindex.index;
            //     var text = "你刚点击了\"";
            //     switch (actionindex) {
            //         case 0:
            //             text += "取消";
            //             break;
            //         case 1:
            if (mui.os.android) {
                var File = plus.android.importClass("java.io.File");
                var Uri = plus.android.importClass("android.net.Uri");
                var MediaStore = plus.android.importClass("android.provider.MediaStore");
                var Intent = plus.android.importClass("android.content.Intent");
                var intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10); //时间限制10秒
                intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 9 * 1024 * 1024); //大小限制9M
                var main = plus.android.runtimeMainActivity();
                main.startActivityForResult(intent, 1);
                main.onActivityResult = function(request, code, data) {
                    var context = main;
                    plus.android.importClass(data);
                    var uri = data.getData();
                    var resolver = context.getContentResolver();
                    plus.android.importClass(resolver);
                    var cursor = resolver.query(uri, null, null, null, null);
                    plus.android.importClass(cursor);
                    cursor.moveToFirst();
                    var column = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                    // 获取录制的视频路径
                    var path = cursor.getString(column);
                    console.log(path);

                    feedback.msgvideo.src = path;
                    feedback.addFile(path);
                    if (path) {
                        feedback.msgvideo.style.display = 'block';
                    }
                    //savevideo(divid, path); 				}
                }
            } else if (mui.os.ios) {
                //录像
                var cmr = plus.camera.getCamera();
                //获取相机 
                cmr.startVideoCapture(function(p) {
                    //录像
                    plus.io.resolveLocalFileSystemURL(p, function(entry) {
                        //通过URL参数获取目录对象或文件对象 就是获取到录像文件位置    
                        var path = entry.toLocalURL();
                        console.log("1111" + path); //打印文件位置，可以直接用作上传路径
                        feedback.msgvideo.src = path + '#t=20';
                        feedback.addFile(path + '#t=20');
                        // document.getElementById("msgvideo").src = path + '#t=20'
                        document.getElementById("msgvideo").style.display = 'block';
                        // document.getElementById("image-up").style.display = none;

                    }, function(e) {
                        console.log("读取录像文件错误：" + e.message);
                    });

                }, function(e) {
                    console.log("失败");
                    plus.nativeUI.toast("录像失败！", {
                        duration: "long"
                    });
                }, {
                    format: 'mp4',
                    filename: '_doc/camera/',
                    index: 1,
                    videoMaximumDuration: 10
                });



            }
            //     break;
            // case 2:
            //     plus.gallery.pick(function(e) {
            //         plus.io.resolveLocalFileSystemURL(e, function(entry) {
            //             var path = entry.toLocalURL();
            //             // 可通过entry对象操作test.html文件 
            //             entry.file(function(file) {
            //                 if (file.size > 10 * 1024 * 1024) {
            //                     alert("您上传的文件过大，请重新选择");
            //                 } else {
            //                     console.log(file.fullPath);
            //                     feedback.msgvideo.src = file.fullPath;
            //                     feedback.addFile(path);
            //                     feedback.msgvideo.style.display = 'block';
            //                 }
            //             });
            //         }, function(e) {
            //             alert("Resolve file URL failed: " + e.message);
            //         });
            //     }, function(error) {
            //         //mui.toast(error.message);
            //     }, {
            //         filter: 'video',
            //         filename: '_doc/camera/',
            //         multiple: false,
            //         maximum: 1,
            //         system: false,
            //         onmaxed: function() {
            //             plus.nativeUI.alert('最多只能选择1个视频');
            //         }
            //     });
            //     break;
            //     }
            // });
        }, false);

        placeholder.appendChild(up);
        placeholder.appendChild(fileInput);
        feedback.videoContainer.appendChild(placeholder);
    };
    feedback.newPlaceholder();

    var state = app.getState();
    var memberToken = state.memberToken;
    var childid = state.childid
    //仅发布至日记

    feedback.sendMsgBtn.addEventListener('tap', function(event) {

        var videosrc = feedback.msgvideo.src;
        if (feedback.msgcontent.value.length == 0 && videosrc.substring(videosrc.length - 4) == 'html') {
            return mui.toast('请输入内容或上传视频')
        }
        //判断网络连接
        if (plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
            return mui.toast("连接网络失败，请稍后再试");
        }

        if (feedback.msgcontent.value != '') {
        	feedback.sendMsgBtn.disabled='disabled';
            mui.post('http://tongban.dqbenxin.com/api/filter', {
                name: feedback.msgcontent.value
            }, function(data) {
                if (data.status == 200) {
                    feedback.send(mui.extend({}, feedback.deviceInfo, {
                        con: feedback.msgcontent.value,
                        type: feedback.msgtype.value.toString(),
                        uid: state.userid.toString(),
                        video: feedback.files,
                        memberToken: memberToken,
                        child_id: childid.toString()
                    }))
                } else if (data.status == 404) {
                	feedback.sendMsgBtn.removeAttribute('disabled');
                    return mui.toast("您输入的内容包含敏感词");
                } else if (data.status == 405) {
                	feedback.sendMsgBtn.removeAttribute('disabled');
                    return mui.toast("输入异常");
                }
            }, 'json');
        } else {
            feedback.send(mui.extend({}, feedback.deviceInfo, {
                con: feedback.msgcontent.value,
                type: feedback.msgtype.value.toString(),
                uid: state.userid.toString(),
                video: feedback.files, 
                memberToken: memberToken, 
                child_id: childid.toString()
            }))
        }



    }, false);

    feedback.send = function(content) {
    	feedback.sendMsgBtn.disabled='disabled'
        var nwaiting;
        feedback.uploader = plus.uploader.createUpload(url, {
            method: 'POST',
        }, function(upload, status) {  
            //上传成功
            console.log(JSON.stringify(status));
            console.log(JSON.stringify(upload));
            var json = JSON.parse(upload.responseText);
            if (status == 200) {
                //mui.fire(plus.webview.getWebviewById("moments"), "refreshmomentmsg", {});
                var wobj = plus.webview.getWebviewById("momentsrefresh");    
                wobj.reload(true);
                mui.fire(plus.webview.getWebviewById("pcenter"), "refreshpoint", {});
                feedback.clearForm();
                plus.webview.currentWebview().close();
                nwaiting.close();
                var toast_txt = "发布成功";
                if (json.point) {
                    toast_txt += ",恭喜您获得" + json.point + "积分";
                }
                mui.toast(toast_txt);
            } else {
                console.log("upload failed");
            }
        });
        //添加上传数据	
        mui.each(content, function(index, element) {

            if (index !== 'video') {
                feedback.uploader.addData(index, element);
            }
        });
        //添加上传文件
        mui.each(feedback.files, function(index, element) {
            var f = feedback.files[index];
            feedback.uploader.addFile(f.path, {
                key: f.name
            });
        });
        //开始上传任务
        feedback.uploader.start();
        nwaiting = plus.nativeUI.showWaiting();
    };
})();